import { useFrame, useLoader } from '@react-three/fiber';
import { useRef, useState } from 'react';
import { Mesh, TextureLoader } from 'three';
import { useIntersect, ScreenSizer, useScroll, DragControls, useCursor, ScrollControls, Text, Billboard, Box } from '@react-three/drei';
import {useStore} from './store'
import { useSpring, animated, config } from '@react-spring/three'

export const Earth: React.FC<{children?: React.ReactNode}> = (props) => {
  const ref = useRef<Mesh>(null!);

  // 鼠标状态
  const [hovered, setHovered] = useState(false)
  useCursor(hovered, /*'pointer', 'auto', document.body*/)

  // scroll 滚动
  const scroll = useScroll()
  useFrame(() => {
    ref.current.rotation.x += scroll.delta * 10;
    ref.current.rotation.y += scroll.delta * 5;
    ref.current.rotation.z += scroll.delta * 7;
  });

  const [ map, normalMap, displacementMap ] = useLoader(TextureLoader, [
    '/earth/earth.png', '/earth/normal.png', '/earth/displacement.jpg'
  ]);

  const setEnter = useStore((state: any) => state.setEnter)
  const setLeave = useStore((state: any) => state.setLeave)

  // click 缩放 动画
  const [active, setActive] = useState(false);
  const {scale} = useSpring({
    scale: active ? 1.5: 1,
    config: config.wobbly // ease
  });

  return <>

    <DragControls>
      <animated.mesh ref={ref} position={[-2, 0.7, -2]} 
        onPointerEnter={() => (setEnter(), setHovered(true))}
        onPointerLeave={() => (setLeave(), setHovered(false))}
        onClick={() => setActive(!active)} scale={scale}
      >
        <sphereGeometry args={[1, 100, 100]} />
        <meshPhongMaterial 
          {...{map, normalMap, displacementMap}}
          displacementScale={0.2}
        />
      </animated.mesh>
    </DragControls>

    <Billboard position={[2, 0, -3]}>
      <Text color='white'>Deri</Text>
    </Billboard>
  </>
}